package gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class LogGatewayFilterFactory extends AbstractGatewayFilterFactory<LogGatewayFilterFactory.Config> {

    public LogGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

                ServerHttpRequest request=exchange.getRequest();
                ServerHttpResponse response=exchange.getResponse();

                String path=request.getURI().getPath();
                String method=request.getMethod().toString();

                System.out.println(config.getBaseMessage()+"请求路径："+path+"请求方式："+method);

                return chain.filter(exchange)
                        .then(Mono.fromRunnable(()->{
                            System.out.println(config.getBaseMessage()+"响应状态码："+response.getStatusCode());
                        }));


            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("baseMessage");
    }

    public static class Config{
        private String baseMessage;

        public String getBaseMessage() {
            return baseMessage;
        }

        public void setBaseMessage(String baseMessage) {
            this.baseMessage = baseMessage;
        }
    }
}
